local newt = reload("newt")
local class = reload("class")
local super = reload("super.database")
local mongoC = require("mongoC")
local conver = require("bson.conver")
local empty = {}


local treply = {
    sour = 1,
    gets = 2,
}

---@class mongoLC : database @mongoLC类
local this = class(super)

function this:ctor(name, info)
    super.ctor(self)
    self._name = name
    self._info = info
    self:closure()
end

function this:launch()
    super.launch(self)
    local info = self._info
    mongoC.new(self._name, info.ip, info.port, info.db, info.user, info.password, self)
    return self:hand()
end

function this:callback(cookid)
    mongoC.callback(cookid)
end

function this:decode(ireply, info, ...)
    if ireply == treply.gets then
        self:listpush(info.args, ...)
    else
        self:nonepush(info.args, ...)
    end
end

function this:listpush(args, ...)
    local len = select("#", ...)
    local lis = newt()
    for i = 1, len do
        local arg = select(i, ...)
        table.insert(lis, arg)
        conver(arg)
    end
    args[1] = lis
end

function this:add(collection, row)
    assert(self._info.write or false, "没有写入权限")
    local cookid = self:cook()
    mongoC.add(cookid, self._name, collection, row)
    return self:watch(treply.sour)
end

function this:adds(collection, rows)
    assert(self._info.write or false, "没有写入权限")
    local cookid = self:cook()
    mongoC.adds(cookid, self._name, collection, rows)
    return self:watch(treply.sour)
end

function this:del(collection, row)
    assert(self._info.write or false, "没有写入权限")
    local cookid = self:cook()
    mongoC.del(cookid, self._name, collection, row)
    return self:watch(treply.sour)
end

function this:dels(collection, row)
    assert(self._info.write or false, "没有写入权限")
    local cookid = self:cook()
    mongoC.dels(cookid, self._name, collection, row)
    return self:watch(treply.sour)
end

function this:cls(collection)
    assert(self._info.write or false, "没有写入权限")
    local cookid = self:cook()
    mongoC.dels(cookid, self._name, collection, empty)
    return self:watch(treply.sour)
end

function this:set(collection, row)
    assert(self._info.write or false, "没有写入权限")
    local cookid = self:cook()
    mongoC.set(cookid, self._name, collection, row)
    return self:watch(treply.sour)
end

function this:get(collection, row)
    local cookid = self:cook()
    mongoC.get(cookid, self._name, collection, row)
    return self:watch(treply.sour)
end

function this:gets(collection, row)
    local cookid = self:cook()
    mongoC.gets(cookid, self._name, collection, row)
    return self:watch(treply.gets)
end

function this:empty()
    local cookid = self:cook()
    mongoC.empty(cookid, self._name)
    return self:watch(treply.sour)
end

function this:await(carg)
    self:empty()(self.coback, self, carg)
    super.await(self, carg)
end

return this
